package LeetCode.month04.day117;

import java.util.Arrays;

/**
 * @author 16778
 * @date 2025/11/27 8:15
 * @description
 */
public class No3381 {
    public long maxSubarraySum(int[] nums, int k) {
        int n = nums.length;
        long res = Long.MIN_VALUE;
        long[] prefixSum = new long[n+1];
        for (int i = 1; i <= n; i++) {
            prefixSum[i] = prefixSum[i-1] + nums[i-1];
        }
        long[] dp = new long[n+1];
        for (int i = k; i <= n; i++) {
            dp[i] = Math.max(dp[i-k]+prefixSum[i]-prefixSum[i-k], prefixSum[i] - prefixSum[i-k]);
            res = Math.max(res, dp[i]);
        }
        return res;
    }

    public long maxSubarraySum2(int[] nums, int k) {
        long[] minS = new long[k];
        Arrays.fill(minS, 0, k - 1, Long.MAX_VALUE / 2); // 防止下面减法溢出

        long ans = Long.MIN_VALUE;
        long s = 0;
        for (int j = 0; j < nums.length; j++) {
            s += nums[j];
            int i = j % k;
            ans = Math.max(ans, s - minS[i]);
            minS[i] = Math.min(minS[i], s);
        }
        return ans;
    }
}
